import 'dart:io';
import 'dart:ui';
import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

import 'Api.dart';

class HttpManager {
  static HttpManager? _httpManager;
  late final Dio _dio;
  CookieJar? _cookieJar;

  factory HttpManager.getInstance() {
    _httpManager ??= HttpManager._internal();
    return _httpManager!;
  }

  HttpManager._internal();
  
  init() async {
    BaseOptions baseOptions = BaseOptions(
      baseUrl: Api.baseUrl,
      receiveTimeout: Duration(milliseconds: 5000),
      sendTimeout: Duration(milliseconds: 3000),
    );
    _dio = Dio(baseOptions);
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options, handler) {
        // 记录请求信息
        print("=====================onRequest start===============================");
        print("Request to: ${options.uri}");
        print("Headers: ${options.headers}");
        print("Body: ${options.data}");
        print("=====================onRequest end===============================");
        return handler.next(options); // 继续执行请求
      },
      onResponse: (response, handler) {
        // 记录响应信息
        print("=====================onResponse start===============================");
        print("Response from: ${response.requestOptions.uri}");
        print("Status code: ${response.statusCode}");
        print('Response data type: ${response.data.runtimeType}');
        print("Data: ${response.data}");

        print("=====================onResponse end===============================");
        return handler.next(response); // 继续执行响应
      },
      onError: (DioException e, handler) {
        // 记录错误信息
        print("=====================onError start===============================");
        print("Error: ${e.message}");
        print("Error type: ${e.type}");
        print("=====================onError end===============================");
        return handler.next(e); // 继续执行错误处理
      },
    ));

    // 根据平台选择不同的 cookie 存储方式
    if (kIsWeb) {
      // Web 平台不使用 cookie 管理器，因为 dio_cookie_manager 不支持 Web
      debugPrint("Running on Web platform - cookie management disabled");
    } else {
      // 移动端使用文件存储
      Directory directory = await getApplicationDocumentsDirectory();
      var path = Directory(join(directory.path, "cookie")).path;
      _cookieJar = PersistCookieJar(storage: FileStorage(path));
      _dio.interceptors.add(CookieManager(_cookieJar!));
    }
  }


  request(url, {data, method = "get"}) async {
    try {
      Options option = Options(method: method);
      Response response = await _dio.request(url, data: data, options: option);
      return response.data;
    } catch (e) {
      return null;
    }
  }

  void clearCookie() {
    if (_cookieJar != null) {
      _cookieJar!.deleteAll();
    }
  }
}
